package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.ExcelExportUtils;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 统计报表
 */
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private ReportService reportService;
    @Reference
    private OrderService orderService;

    /**
     * 会员统计折线图
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        Map<String,Object> map = new HashMap<>();
        List<String> months = new ArrayList<>();
        //使用模拟数据测试是否能转为echarts所需的格式
        /*months.add("2019.05");
        months.add("2019.06");
        months.add("2019.07");
        months.add("2019.08");
        months.add("2019.09");*/
        //获得日历对象，模拟时间就是当前时间
        Calendar calendar = Calendar.getInstance();
        //计算过去一年的12个月
        calendar.add(Calendar.MONTH,-12);//获得当前时间往前推12个月的时间
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH,1);//获得日历对象当前时间往后推一个月
            Date date = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy.MM").format(date));
        }

        map.put("months",months);

        List<Integer> memberCount = memberService.findMemberByMonths(months);
        /*memberCount.add(3);
        memberCount.add(3);
        memberCount.add(4);
        memberCount.add(6);
        memberCount.add(8);*/

        map.put("memberCount",memberCount);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }
    /**
     * @Author Fanghao
     * @Description 预约/到诊统计折线图
     * @Date Created in 2020/10/9 14:28
     * @param
     * @return Result
     */
    @RequestMapping("/getOrderReport")
    public Result getOrderReport(){
        Map<String,Object> map = new HashMap<>();
        List<String> dates = orderService.findOrderDate();
        map.put("date",dates);
        List<Integer> todayOrderNumberCount = new ArrayList<>();

        for (String date : dates) {
            Integer count = orderService.findOrderCount(date);
            todayOrderNumberCount.add(count);
        }

        List<Integer> todayVisitsNumberCount = new ArrayList<>();

        for (String date : dates) {
            Integer count2 = orderService.findOrderStatusCount(date);
            todayVisitsNumberCount.add(count2);
        }
        map.put("todayOrderNumberCount",todayOrderNumberCount);
        map.put("todayVisitsNumberCount",todayVisitsNumberCount);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }

    /**
     * 套餐预约统计饼形图
     * @return
     */
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        try {
            Map<String,Object> map = new HashMap<>();
            //模拟数据
            List<Map<String,Object>> setmealCount = setmealService.findsetmealCount();
        /*Map<String,Object> map1 = new HashMap<>();
        map1.put("name","直接访问");
        map1.put("value",200);
        setmealCount.add(map1);

        Map<String,Object> map2 = new HashMap<>();
        map2.put("name","邮件营销");
        map2.put("value",300);
        setmealCount.add(map2);*/

            map.put("setmealCount",setmealCount);


            List<String> setmealNames = new ArrayList<>();
        /*setmealNames.add("直接访问");
        setmealNames.add("邮件营销");*/
            for (Map<String, Object> stringObjectMap : setmealCount) {
                String name = (String) stringObjectMap.get("name");
                setmealNames.add(name);
            }

            map.put("setmealNames",setmealNames);

            return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }


    /**
     * @Author Fanghao
     * @Description 套餐收入统计饼形图
     * @Date Created in 2020/10/9 11:00
     * @param
     * @return Result
     */
    @RequestMapping("/getSetmealIncomeStatistics")
    public Result getSetmealIncomeStatistics(){
        Map<String, Object> data = new HashMap<>();
        try {
            List<Map<String, Object>> SetmealIncomeStatistics = setmealService.findSetmealIncomeStatistics();
            List<String> setmealNames = new ArrayList<>();
            // map1为总收入
            Map map1 = new HashMap();
            // sum为总收入的值
            int sum = 0;
            for (Map<String, Object> map : SetmealIncomeStatistics) {
                // 取出套餐名字
                String name = (String) map.get("name");
                // 添加到tatle中
                setmealNames.add(name);
                // 取出每个套餐的总收入
                Double setmealIncome = (Double) map.get("value");
                // 赋值给变量sum
                sum += setmealIncome;
            }
            map1.put("name","总收入");
            map1.put("value",sum);
            setmealNames.add("总收入");
            SetmealIncomeStatistics.add(map1);

            data.put("setmealNames",setmealNames);
            data.put("SetmealIncomeStatistics",SetmealIncomeStatistics);
            return new Result(true,"套餐收入占比查询成功",data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "套餐收入占比查询失败");
        }
    }

    /**
     * @Author Fanghao
     * @Description TODO 统计会员的年龄分布未完成
     * @Date Created in 2020/10/9 15:58
     * @param
     * @return Result
     */
    @RequestMapping("/getMemberAgeReport")
    public Result getMemberAgeReport(){
        return null;
    }

    /**
     * 运营数据统计
     * @return
     */
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            Map<String,Object> data = reportService.getBusinessReport();
            //使用模拟数据进行测试
        /*data.put("reportDate","2020.09.09");
        data.put("todayNewMember",100);
        data.put("totalMember",20000);
        data.put("thisWeekNewMember",300);
        data.put("thisMonthNewMember",500);
        data.put("todayOrderNumber",150);
        data.put("todayVisitsNumber",100);
        data.put("thisWeekOrderNumber",300);
        data.put("thisWeekVisitsNumber",290);
        data.put("thisMonthOrderNumber",500);
        data.put("thisMonthVisitsNumber",400);

        List<Map<String,Object>> hotSetmeal = new ArrayList<>();
        Map<String,Object> map1 = new HashMap<>();
        map1.put("name","阳光爸妈升级肿瘤12项筛查（男女单人）体检套餐");
        map1.put("setmeal_count",200);
        map1.put("proportion",0.222);

        Map<String,Object> map2 = new HashMap<>();
        map2.put("name","阳光爸妈升级肿瘤12项筛查体检套餐");
        map2.put("setmeal_count",100);
        map2.put("proportion",0.111);

        hotSetmeal.add(map1);
        hotSetmeal.add(map2);

        data.put("hotSetmeal",hotSetmeal);*/

            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 导出excel
     * @return
     */
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            //远程调用报表服务获取报表数据
            Map<String,Object> result = reportService.getBusinessReport();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            String fileName = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            //基于提供的excel模板文件在内存中创建一个Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(fileName)));
            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);
            //获得第三行第六列
            XSSFRow row = sheet.getRow(2);
            XSSFCell cell = row.getCell(5);
            cell.setCellValue(reportDate);  //日期
            
            //获得第五行第六列
            row = sheet.getRow(4);
            cell = row.getCell(5);
            cell.setCellValue(todayNewMember);//新增会员数（本日）

            //获得第五行第八列
            row = sheet.getRow(4);
            cell = row.getCell(7);
            cell.setCellValue(totalMember);//总会员数

            //获得第六行第六列
            row = sheet.getRow(5);
            cell = row.getCell(5);
            cell.setCellValue(thisWeekNewMember);//本周新增会员数

            //获得第六行第八列
            row = sheet.getRow(5);
            cell = row.getCell(7);
            cell.setCellValue(thisMonthNewMember);//本月新增会员数

            //获得第八行第六列
            row = sheet.getRow(7);
            cell = row.getCell(5);
            cell.setCellValue(todayOrderNumber);//今日预约数

            //获得第八行第八列
            row = sheet.getRow(7);
            cell = row.getCell(7);
            cell.setCellValue(todayVisitsNumber);//今日到诊数

            //获得第九行第六列
            row = sheet.getRow(8);
            cell = row.getCell(5);
            cell.setCellValue(thisWeekOrderNumber);//本周预约数

            //获得第九行第八列
            row = sheet.getRow(8);
            cell = row.getCell(7);
            cell.setCellValue(thisWeekVisitsNumber);//本周到诊数

            //获得第十行第六列
            row = sheet.getRow(9);
            cell = row.getCell(5);
            cell.setCellValue(thisMonthOrderNumber);//本月预约数

            //获得第十行第八列
            row = sheet.getRow(9);
            cell = row.getCell(7);
            cell.setCellValue(thisMonthVisitsNumber);//本月到诊数

            //获得第五行第六列
            row = sheet.getRow(4);
            cell = row.getCell(5);
            cell.setCellValue(todayNewMember);

            int rowNum = 12;
            for (Map map : hotSetmeal) {//热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");

                row = sheet.getRow(rowNum++);
                cell = row.getCell(4);
                cell.setCellValue(name);//套餐名称

                cell = row.getCell(5);
                cell.setCellValue(setmeal_count);//预约数量

                cell = row.getCell(6);
                cell.setCellValue(proportion.doubleValue());//占比

            }

            //基于浏览器下载
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表是excel文件
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//以附件形式进行下载

            excel.write(outputStream);
            outputStream.flush();
            outputStream.close();
            excel.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 导出PDF
     * @return
     */
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response){
        try {
            Map<String, Object> result = reportService.getBusinessReport();

            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";
            //编译模板
            JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);
            //填充数据
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            JasperPrint jasperPrint =JasperFillManager.fillReport(jasperPath,result,new JRBeanCollectionDataSource(hotSetmeal));

            //基于浏览器下载
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/pdf");//代表是excel文件
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");//以附件形式进行下载
            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint,outputStream);

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }






    @RequestMapping("/batchExport")
    public void   batchExport(HttpServletResponse response, @RequestBody List<Member> excelDate) throws Exception {


        ServletOutputStream out=response.getOutputStream();

        //设置文件头：最后一个参数是设置下载文件名

        //  response.setContentType("application/binary;charset=UTF-8");

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(1+".xls", "UTF-8"));

        String[] titles = { "档案号", "姓名", "性别", "出生日期","健康管理师","手机号码","注册时间" };

        String[][] datas;

        datas=new String[excelDate.size()][titles.length];

        for (int i = 0; i < excelDate.size(); i++) {
            Member member = excelDate.get(i);

            datas[i][0] = member.getFileNumber();
            datas[i][1] = member.getName();
            datas[i][2] = member.getSex();

            datas[i][3] =  DateUtils.parseDate2String(member.getBirthday());
            datas[i][4] = member.getUsername();
            datas[i][5] =  DateUtils.parseDate2String(member.getRegTime());

        }

        //调用导出excel文件方法
        ExcelExportUtils.export(titles,datas, out);

    }
}
